import { Component, Vue } from 'vue-property-decorator'
import styles from './Login.less'

import { State, Action, Mutation } from 'vuex-class'
import { RootState } from '@/store'
import { LoginState } from '@/store/modules/login'
import { ElForm } from 'element-ui/types/form'
const code = require('@/assets/code.png')
const codeHover = require('@/assets/code-hover.png')
const computer = require('@/assets/computer.png')
const computerHover = require('@/assets/computer-hover.png')

const loginRule = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[0-9]{10}$/,
      message: '手机号格式不正确',
      trigger: 'blur',
    },
  ],
  licenseNumber: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    {
      pattern: /^(([0-9]{14})|([0-9]{17}))([0-9]|X|x)$/,
      message: '身份证格式不正确',
      trigger: 'blur',
    },
  ],
  username: [{ required: true, message: '请输入申请人姓名', trigger: 'blur' }],
  // code: [
  //   { required: true, message: "请输入验证码", trigger: "blur" },
  //   { len: 4, message: "长度不正确", trigger: "blur"}
  // ],
  mobileCode: [
    { required: true, message: '请输入手机验证码', trigger: 'blur' },
    { len: 6, message: '长度不正确', trigger: 'blur' },
  ],
}

@Component({})
export default class About extends Vue {
  @State((state: RootState) => state.login)
  private loginData!: LoginState
  private showCode = false
  private codeImg = ''
  private img = code
  private loading = false
  // private mobileCodeInfo: string = ''
  private countDownTime: number = 0
  private timer: any = null
  private sendDisabled: boolean = false

  @Action('login/login') private loginHandler!: any
  @Action('login/sendMobileCode') private sendMobileCode!: any
  @Mutation('login/setStateData') private setStateData!: any

  get loginCode() {
    if (this.showCode) {
      return computer
    }

    return code
  }

  get hoverLoginCode() {
    if (this.showCode) {
      return computerHover
    }

    return codeHover
  }

  protected render() {
    return (
      <div class={styles.container}>
        <div class={styles.backOld}>
          {/* <el-button class="btn-href" onClick={this.toOpen}>开放平台</el-button> */}
          <el-button
            class="btn-href"
            onClick={this.toManage}
            style={{ width: '115px' }}
          >
            电子印章管理系统
          </el-button>
          {/* 暂不显示下载功能 <el-button class="btn-href" onClick={this.download}>下载客户端</el-button> */}
          <el-button class="btn-href" onClick={this.toOld}>
            前往旧版
          </el-button>
          <el-button class="btn-href" onClick={this.toHelp}>
            技术支持
          </el-button>
        </div>
        <p>
          <img class={styles.logo} src={require('@/assets/logo.png')} />
          {/* <span class={styles.titles}>浙江省政府统一电子印章申请系统<br />https://seal.zj.gov.cn/</span> */}
        </p>
        <el-form
          {...{ props: { model: this.loginData, rules: loginRule } }}
          ref="loginForm"
          class={styles.loginComponent}
        >
          <div class={styles.transform}>
            <el-tooltip
              effect="dark"
              content={this.showCode ? '去登录' : '扫码加入'}
              placement="left-start"
            >
              <img
                src={this.img}
                onMouseover={() => {
                  this.img = this.hoverLoginCode
                }}
                onMouseout={() => {
                  this.img = this.loginCode
                }}
                onClick={() => {
                  this.showCode = !this.showCode
                  if (this.showCode) {
                    this.img = computerHover
                  } else {
                    this.img = codeHover
                  }
                }}
              />
            </el-tooltip>
          </div>
          <div v-show={!this.showCode}>
            <p class={styles.title}>可使用在本印章系统或政务ca网站注册的账号</p>
            <el-form-item prop="licenseNumber" ref="" label-width="0">
              <el-input
                v-model={this.loginData.licenseNumber}
                placeholder="请输入申请人身份证号码"
                autocomplete="off"
                onBlur={() =>
                  this.inputToTrim(
                    this.loginData.licenseNumber,
                    'licenseNumber'
                  )
                }
              />
            </el-form-item>
            <el-form-item prop="username" label-width="0">
              <el-input
                v-model={this.loginData.username}
                placeholder="请输入申请人姓名"
                autocomplete="off"
                onBlur={() =>
                  this.inputToTrim(this.loginData.username, 'username')
                }
              />
            </el-form-item>
            <el-form-item prop="phone" label-width="0">
              <el-input
                v-model={this.loginData.phone}
                placeholder="请输入申请人手机号"
                autocomplete="off"
                onBlur={() => this.inputToTrim(this.loginData.phone, 'phone')}
              />
            </el-form-item>
            {/* <el-form-item prop="code" class="code-item" label-width="0">
              <el-input
                class="input-code"
                v-model={this.loginData.code}
                placeholder="请输入图片验证码"
                autocomplete="off"
              />
              <img class="image" onClick={this.refresh} ref="codeImage" alt="验证码" />
            </el-form-item> */}
            <el-form-item prop="mobileCode" class="code-item" label-width="0">
              <el-input
                class="input-code"
                v-model={this.loginData.mobileCode}
                placeholder="请输入手机收到的验证码"
                autocomplete="off"
                onBlur={() =>
                  this.inputToTrim(this.loginData.mobileCode, 'mobileCode')
                }
              />
              <button
                class={styles.mobileCode}
                onClick={this.getMobileCode}
                disabled={!!this.countDownTime || this.sendDisabled}
              >
                {this.countDownTime ? `${this.countDownTime}s` : '发送验证码'}
              </button>
            </el-form-item>
            <el-button
              class={{
                [styles.loginBtn]: true,
                'btn-primary': true,
                'btn-primary-hover': this.validField(),
              }}
              loading={this.loading}
              {...{
                on: {
                  click: this.login,
                },
              }}
            >
              登录
            </el-button>
            <p class={styles.tips}>
              没有账号？
              <router-link to="/signup">点击注册</router-link>
            </p>
          </div>
          <div v-show={this.showCode} class={styles.qrCode}>
            <img src={require('@/assets/login-qrcode.jpg')} alt="" />
            <p class={styles.title}>{window.config.dingGroup}</p>
            <p class={styles.tips}>
              使用手机钉钉APP扫码加入，以获得更多技术支持
            </p>
            <p class={styles.info}>
              钉钉群名称：浙江省政府电子印章交流群
              <br />
              钉钉群号：30001457
            </p>
          </div>
        </el-form>
        <div class={styles.footer}>
          <div class="box">
            <p>服务热线：4000878198转3(政务服务专线) </p>
            <p>
              主办单位：浙江省大数据发展管理局
              技术支持：杭州天谷信息科技有限公司
            </p>
          </div>
        </div>
      </div>
    )
  }

  private login() {
    const form = this.$refs.loginForm as ElForm
    form.validate(async (valid: boolean) => {
      if (valid) {
        this.loading = true
        this.loginHandler()
          .then((res: any) => {
            this.loading = false
            this.$router.push({ name: 'home' })
          })
          .catch((e: any) => {
            this.loading = false
            // this.refresh();
          })
      }
    })
  }

  private inputToTrim(v: any, key: string) {
    this.loginData[key] = v.trim()
  }

  private reset() {
    this.setStateData({
      licenseNumber: '',
      username: '',
      code: '',
      phone: '',
      mobileCode: '',
      // 标记是注册状态
      signUpFlag: false,
    })
    this.$nextTick(() => {
      ;(this.$refs.loginForm as ElForm).clearValidate()
    })
  }
  private mounted() {
    this.reset()
    // this.refresh();
  }
  private refresh() {
    const src = `/seal/rest/account/generateCaptcha?t=${Math.random()}`
    const codeImage = this.$refs.codeImage as HTMLImageElement
    codeImage.src = src
  }

  private download() {
    window.open(window.config.downloadClientUrl, '_blank')
  }

  private key() {}

  private toOld() {
    window.location.href = window.config.oldVersionUrl
  }

  private toOpen() {
    window.location.href = window.config.openSystemUrl
  }

  private toHelp() {
    window.open(`${window.location.origin}/support`, '_blank')
  }

  private toManage() {
    window.location.href = window.config.manageSystemUrl
  }

  private validField() {
    const { licenseNumber, username, phone, mobileCode } = this.loginData

    return !!licenseNumber && !!username && !!phone && !!mobileCode
  }

  private getMobileCode(e: Event) {
    e.stopPropagation()
    e.preventDefault()
    let hasErr = false

    this.loginData.mobileCode = ''

    const from = this.$refs.loginForm as ElForm
    from.validateField(['phone', 'licenseNumber', 'username'], data => {
      if (!!data) {
        hasErr = true
      }
    })

    if (hasErr) return
    this.sendDisabled = true
    this.sendMobileCode({
      mobile: this.loginData.phone,
    })
      .then((res: any) => {
        this.sendDisabled = false
        if (!this.countDownTime) {
          this.countDownTime = 90
          this.countDown()
        }
      })
      .catch((e: any) => {
        this.sendDisabled = false
      })
  }

  private countDown() {
    if (this.countDownTime <= 0) {
      clearTimeout(this.timer)

      return
    }

    this.timer = setTimeout(() => {
      this.countDownTime--
      this.countDown()
    }, 1000)
  }
}
